vali_cohort_dir <- read_lines("/Pub/Users/wangyk/project/Poroject/230915001_CESC/data/vali_cohort_dir.tsv")

f <- \(x){
    # x = 3
    basename(vali_cohort_dir[x]) %>% cli::cli_h2()

    fs <- list.files(vali_cohort_dir[x], full.names = T)

    c("/expression.RData", "/clinical.RData") %>%
        map(~ str_detect(fs, pattern = .x) %>% which()) %>%
        unlist() -> i

    fs[i] %>% walk(~ load(.x, envir = .GlobalEnv))

    colnames(clinical)

    clin_tmp <- clinical %>%
        rename(time = OS.Time, status = OS.Status, sample = Sample) %>%
        filter(time > 0)

    vali_res <- KM_ROC_curve(
        model_coef = coef_df,
        exp = expression,
        clinical = clin_tmp,
        surtime_unit = c(365),
        saveplot = F,
        output_dir = "./out/model",
        var_name = basename(vali_cohort_dir[x]),
        ROC_time_break = c(1, 3, 5),
        best_cut = T,
        manual_cutoff = NULL,
        do_ROC_CI = F,
        savetiff = F
    )

    eff_res <- Effectiveness_Analysis(
        model_coef = coef_df, exp = expression, clinical = clin_tmp, surtime_unit = 365,
        saveplot = F, output_dir = "out/model/output/", var_name = basename(vali_cohort_dir[x]),
        dataset = NULL,
        KM_ROC_res = vali_res
    )

    p <- eff_res[["1_5p"]] + plot_annotation(
        title = basename(vali_cohort_dir[x])
    )

    ggsave(
        plot = p, filename = str_glue("out/model/output/EFF_{basename(vali_cohort_dir[x])}.pdf"),
        width = 9.5, height = 10
    )

    vali_res[[3]] %>%
        inner_join(clin_tmp) %>%
        rename(Score = riskgroup) -> df

    feature <-  c("Score", "Age", "Stage", "Sex")

    feature %in% colnames(df) %>% which() -> i2

    # c("Age",'Stage','Sex')[i2]

    if ("Age" %>% is_in(feature[i2])) {
        df %<>% mutate(Age = ifelse(Age > 60, ">60", "<=60"))
    }

    if (length(i2) == 1) {
        return()
    } else {
        aa <- Forest_DF(
            clinical = df,
            features_col = feature[i2],
            SaveFile = T, od = "out/model/output/independence/", w = 5, h = 3, p_cut = 2,
            var_name = basename(vali_cohort_dir[x]),
            cohort = basename(vali_cohort_dir[x])
        )
    }
}

walk(seq_along(vali_cohort_dir), f)
